<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>


    <script>

        class EventEmitter extends EventTarget {
            on = this.addEventListener;

            off = this.removeEventListener;

            emit = (type, data) => this.dispatchEvent(new CustomEvent(type, { detail: data }));

            once = (type, listener) => this.on(type, listener, { once: true, capture: true });
        }

    </script>


    <script>

        var emitter = new EventEmitter();
        function onEventX(ev) {
            console.log("event-x 收到数据:", ev.detail);
        }

        // 订阅
        emitter.on("event-x", onEventX);
        emitter.once("event-once", ev => console.log("event-once 收到数据:", ev.detail));

        // 发布
        emitter.emit("event-once", { uid: -100, message: "you love me" });
        emitter.emit("event-once", { uid: -100, message: "you love me" });

        emitter.emit("event-x", { uid: 100, message: "i love you" })
        emitter.off("event-x", onEventX);
        emitter.emit("event-x", { uid: 100, message: "i love you" })

    </script>

</body>

</html>